#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os

import util.excel_util as eu
import util.reg_util as ru
import util.x_crypto_util as xu

# 服务器配置EXCEL文件
source_file = ''
# 工作表名称集合
sheet_names = [
    'shit1',
    'shit2'
]
# 工作表列配置映射
excel_conf_mapping = eu.XConfColumnStrMapping(
    'D', 'E', 'H', 'I', 'B', 'F', 'G', 'J', 'K', 'L'
)
# 生成的配置文件存放位置（不指定则生成到XShell默认配置文件目录）
target_dir = ''
# XShell版本（在XShell中任意创建SSH配置文件，以文本方式打开，查找其中Version字段的值）
xshell_version = 7.1
# 生成的SHH配置是否使用跳板机
using_jumpserver = True
# 跳板机配置
jump_server_conf = {
    'host': '110.110.110.110',
    'port': 666,
    'username': '程磊',
    'password': '你猜',
    'user_key': '母鸡',
    'method': 0,  # 0-密码；1-密钥
    'default_user': 'bestseller'
}


def generate_xsh_confs(target_path: str, conf_using_jumpserver: bool):
    # 从EXCEL解析工作表集合
    sheets: list = eu.read_sheets_from_excel(source_file, sheet_names)
    crypto = xu.XShellCrypto(xshell_version)
    for sheet in sheets:
        # sheet: Worksheet = sheet
        # 每个工作表生成的配置文件为一组，放到每组单独的目录中
        conf_group_dir = target_path + os.sep + sheet.title
        for row_no in range(sheet.max_row):
            # 跳过标题行
            if row_no == 0:
                continue
            display_no = str(row_no + 1)
            # 读取配置
            server_conf = {
                'host': sheet[excel_conf_mapping.host + display_no].value,
                'port': sheet[excel_conf_mapping.port + display_no].value,
                'username': sheet[excel_conf_mapping.username + display_no].value,
                'password': sheet[excel_conf_mapping.password + display_no].value,
                'role': sheet[excel_conf_mapping.role + display_no].value,
                'cluster_id': sheet[excel_conf_mapping.cluster_id + display_no].value,
                'app_dir': sheet[excel_conf_mapping.app_dir + display_no].value,
                'cd_app_dir': sheet[excel_conf_mapping.cd_app_dir + display_no].value,
                'conf_sub_dir': sheet[excel_conf_mapping.conf_sub_dir + display_no].value,
                'remark': sheet[excel_conf_mapping.remark + display_no].value,
            }
            # 拼接目标文件全路径
            conf_path: str = conf_group_dir
            if server_conf['conf_sub_dir']:
                conf_path = conf_path + os.sep + server_conf['conf_sub_dir']
            if not os.path.exists(conf_path):
                os.makedirs(conf_path)
            if server_conf['cluster_id']:
                file_name = server_conf['role'] + '-' + str(server_conf['cluster_id'])
            else:
                file_name = server_conf['role']
            if xu.is_private_ip(server_conf['host']):
                ip_suffix = server_conf['host'].split('.', 2)[2]
            else:
                ip_suffix = server_conf['host']
            target_file = conf_path + os.sep + file_name + '[' + ip_suffix + '].xsh'
            print('创建【' + target_file + '】，配置：' + str(server_conf))
            # 生成XShell配置文件内容
            xsh_conf = xu.generate_xshell_conf(crypto, server_conf, conf_using_jumpserver, jump_server_conf)
            # 将配置文件内容写入到xsh文件
            with open(target_file, 'w', encoding='utf-16') as f:
                f.writelines(xsh_conf)
            f.close()


if __name__ == '__main__':
    if target_dir:
        target_conf_dir = target_dir
    else:
        target_conf_dir = ru.get_user_folder_path('Personal') + '\\NetSarang Computer\\' + str(int(xshell_version)) + '\\Xshell\\Sessions'
    print('生成目标目录：' + target_conf_dir)
    generate_xsh_confs(target_conf_dir, using_jumpserver)
